import time
import math
import json


def best_square_approximation(x_values, y_values):
    n = len(x_values)
    x_mean = sum(x_values) / n
    y_mean = sum(y_values) / n
    ssr = 0  # Sum of Squared Residuals
    for x, y in zip(x_values, y_values):
        y_pred = x ** 2 * a + x * b + c
        ssr += (y - y_pred) ** 2
        a, b, c = 0, 0, 0  # Reset coefficients
        for i in range(n):
            a += (x_values[i] - x_mean) * (y_values[i] - y_mean)
            b += (x_values[i] - x_mean) ** 2
            c += (x_values[i] - x_mean) * (y_values[i] - y_mean)
    a = ssr / b
    b = (ssr / b) * (-1)
    c = y_mean - a * x_mean - b * x_mean
    res = f"The best square approximation is y = {a}x^2 + {b}x + {c}."
    return a, b, c


def handle(req):
    st = time.time()
    """handle a request to the function
    Args:
        req (str): request body
    """
    jsonObj = json.loads(req)
    x = jsonObj["x"]
    y = jsonObj["y"]
    res = best_square_approximation(x, y)

    et = time.time()
    return (et - st) * 1000


if __name__ == "__main__":
    data = {
        "x": [1, 2, 3, 4, 5],
        "y": [2, 4, 6, 8, 10]
    }
    res = handle(json.dumps(data))
    print(type(res))
    print(res)
